//
//  NSArray+NN.m
//  TempletProject
//
//  Created by lina on 15/11/4.
//  Copyright © 2015年 张 坤. All rights reserved.
//

#import "NSArray+NN.h"

@implementation NSArray (NN)
- (NSString *)JSONString
{
    NSError * error;
    NSData *data = [NSJSONSerialization dataWithJSONObject:self options:NSJSONWritingPrettyPrinted error:&error];
    return [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
}

+ (instancetype)arrayWithJSONString:(NSString *)string
{
    NSData *resultData = [string dataUsingEncoding:NSUTF8StringEncoding];
    NSError *error = nil;
    return [NSJSONSerialization JSONObjectWithData:resultData
                                           options:NSJSONReadingAllowFragments
                                             error:&error];;
}

-(NSString *)stringSeparatedByString:(NSString *)separator {
    NSMutableString * str = [NSMutableString new];
    for (id v in self) {
        if (str.length > 0) [str appendString:separator];
        [str appendFormat:@"%@",v];
    }
    return str;
}

- (NSString *)stringSeparatedByString:(NSString *)separator withBlock:(NSString * (^)(id))block
{
    NSParameterAssert(block != nil);
    
    __block NSMutableString * str = [NSMutableString new];
    
    [self enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        if (str.length > 0) [str appendString:separator];
        NSString * result = block(obj);
        if (result && result.length > 0) {
            [str appendString:result];
        }
    }];
    
    return str;
}

- (NSArray *)map:(id (^)(id obj))block {
    NSParameterAssert(block != nil);
    
    NSMutableArray *result = [NSMutableArray arrayWithCapacity:self.count];
    
    [self enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        id value = block(obj) ?: [NSNull null];
        [result addObject:value];
    }];
    
    return result;
}
@end
